package com.travel.travelnetwork.service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.travel.travelnetwork.bean.PermissionWithStatus;
import com.travel.travelnetwork.mapper.PermissionMapper;
import com.travel.travelnetwork.mapper.RoleMapper;
import com.travel.travelnetwork.pojo.Permission;
import com.travel.travelnetwork.pojo.Role;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class RoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PermissionMapper permissionMapper;

    //查询所有用户
    public Page<Role> findPage(int page,int size) {
        return roleMapper.selectPage(new Page<>(page,size),null);
    }
    //新增角色
    public void  addRole(Role role) {
        roleMapper.insert(role);
    }

    //查询角色
    public Role findRoleById(Integer rid) {
        return roleMapper.selectById(rid);
    }

    //修改角色
    public void updateRole(Role role) {
        roleMapper.updateById(role);
    }

    //删除角色
    public void deleteRole(Integer rid) {
        roleMapper.deleteById(rid);
    }

    //修改角色权限
    public List<PermissionWithStatus> findAllPermissions(Integer rid) {
        List<Permission> permissions = permissionMapper.selectList(null);
        List<Integer> permissionIdByRoles = permissionMapper.findPermissionIdByRole(rid);
        List<PermissionWithStatus> permissionWithStatuslist = new ArrayList<>();
        for (Permission permission : permissions) {
            PermissionWithStatus permissionWithStatus = new PermissionWithStatus();
            BeanUtils.copyProperties(permission, permissionWithStatus);
            if(permissionIdByRoles.contains(permission.getPid())){
                permissionWithStatus.setRoleHas(true);
            }
            else{
                permissionWithStatus.setRoleHas(false);
            }
            permissionWithStatuslist.add(permissionWithStatus);
        }
        return permissionWithStatuslist;
    }
    public void roleUpdataPermission(Integer rid, Integer[] ids) {
        roleMapper.deleteRoleByPermission(rid);
        if(ids != null){
            for (Integer pid : ids) {
                roleMapper.addRoleToPermission(rid, pid);
            }
        }
    }
}
